import React from 'react';
import cn from 'classnames';
import { Checkbox, Helper } from '@knownsec/react-component';
import s from './CheckboxGroup.module.css';

function CheckboxGroup({
  className,
  checked: checkedProps = {},
  options,
  onChange,
  checkboxClassName,
  tipProps,
  ...props
}) {
  const [checkedState, setChecked] = React.useState({});
  const checked = checkedState;
  const handleCheck = (nextChecked) => {
    setChecked(nextChecked);
    onChange(nextChecked);
  };
  React.useEffect(() => {setChecked(checkedProps)},[checkedProps])
  return (
    <span className={cn(className, s.checkboxGroup)}>
      {options.map(({ value, label,disabled, ...prop }) => {
        return (
          <span key={value} className={s.checkboxContainer}>
            <Checkbox
              {...props}
              key={value}
              disabled={disabled===undefined?props.disabled:disabled}
              className={cn(s.checkbox, checkboxClassName)}
              checked={checkedState[value]}
              onChange={(e) => {
                handleCheck({
                  ...checked,
                  [value]: e.value,
                });
              }}
            >
              {label}
            </Checkbox>
            {prop?.tip && (
              <Helper
                className="paddingHelp"
                overlayClassName={s.helpTooltip}
                overlay={prop?.tip}
                placement="top"
                {...(prop?.tipProps || {})}
              />
            )}
          </span>
        );
      })}
    </span>
  );
}

CheckboxGroup.defaultProps = {
  className: s.CheckboxGroup,
  // 是否单选
  single: false,
  borderless: false,
  onChange: () => {},
  tipProps: {},
};

export default CheckboxGroup;
